import React, { useState, useEffect } from "react"
import { Card, Form, Input, Button, Select, Table, message, Space } from "antd"
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from "react-router-dom"
// 请求接口
import {
  addHospitalList,
  modifyState,
  provincialLevel,
  MunicipalLevel,
} from "@api/hospitalList"

// 类型接口
import { Status, submitPagingList } from "@api/hospitalList/model"
const { Option } = Select

const Index = () => {
  // 省市区状态设定
  const [provinceData, setprovinceData] = useState<any>([]) // 省
  const [CityName, setCityName] = useState<any>([]) // 市
  const [cityData, septicityData] = useState<any>([]) // 区
  // 表格加载中
  const [loading, setLoading] = useState<any>(false)

  // 自请求渲染状态
  let [data, setState] = useState<any>([])
  // 分页状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState()
  // 保存医院级别
  const [values, setValues] = useState<any>([])

  const navigate = useNavigate()
  const [form] = Form.useForm()
  // 上下线
  const UpDownLine = (id: string, status: Status) => {
    return async () => {
      // 传递id和状态，发送请求修改状态，返回值重新渲染页面
      await modifyState(id, +!status)
      message.success("状态更新成功")
      paging(page, pageSize)
    }
  }
  // 挂载
  useEffect(() => {
    const getList = async () => {
      const data = await addHospitalList({ page, pageSize })
      setState(data.content)
      // 获取省数据,保存数据
      const res = await provincialLevel()
      setprovinceData(res)
      // 获取医院等级

      const vas = await MunicipalLevel("10000")
      setValues(vas)
    }
    getList()
  }, [])

  // 定义列
  const columns: any = [
    {
      title: "序号",
      width: 70,
      align: "center" as "center",
      render: (_x: any, _y: any, index: number) => {
        return index + 1
      },
    },
    {
      title: "医院logo",
      width: 90,
      dataIndex: "logoData",
      render: (logo: string) => (
        // base64图片技术
        // 找到一张base64格式图片，观察我们数据缺少了哪部分。加上去即可
        <img
          className="hospital-img"
          src={"data:image/jpeg;base64," + logo}
          alt="logo"
          style={{ width: 100 }}
        />
      ),
    },
    {
      title: "医院名称",
      width: 320,
      dataIndex: "hosname",
    },
    {
      title: "等级",
      width: 150,
      render: (text: any) => {
        return text.param.hostypeString
      },
    },
    {
      title: "详细地址",
      width: 320,
      render: (text: any) => {
        return text.param.fullAddress
      },
    },
    {
      title: "状态",
      width: 100,
      align: "center" as "center",
      dataIndex: "status",
      // dataIndex和render同时使用，render第一个参数拿到的就是dataIndex指定的值
      render: (status: Status) => {
        return status ? "已上线" : "未上线"
      },
    },
    {
      title: "创建时间",
      width: 200,
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 300,
      render: (text: any) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              detailsView(text.id)
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            onClick={() => {
              Scheduling(text.hoscode)
            }}
          >
            排班
          </Button>
          <Button type="primary" onClick={UpDownLine(text.id, text.status)}>
            {text.status ? "下线" : "上线"}
          </Button>
        </Space>
      ),
    },
  ]
  // 点击查看跳转页面
  const detailsView = (id: string) => {
    navigate(`/syt/hospital/hospitalList/show/${id}`)
  }
  // 点击跳转排班页面
  const Scheduling = (hoscode: string) => {
    navigate(`/syt/hospital/hospitalList/schedule/${hoscode}`)
  }

  // 条件查询
  const queryCondition = async (values: any) => {
    setLoading(true) // 加载中
    // valus可以拿到name属性的值，根据数据判断查找
    data = await addHospitalList({ page, pageSize, ...values }) // 获取数据
    setState(data.content)
    setTotal(data.totalElements) // 修改总数
    setPage(page) // 修改当前页面
    setPageSize(pageSize) // 修改当前页面数据条数
    message.success("查找成功")
    setLoading(false)
  }

  // 查询函数
  const paging = async (page: number, pageSize: number) => {
    setLoading(true) // 加载中
    const data = await addHospitalList({ page, pageSize }) // 获取数据

    setPage(page) // 修改当前页面
    setPageSize(pageSize) // 修改当前页面数据条数
    // 根据响应数据,修改total,动态渲染表格
    setState(data.content) // 渲染页面
    setTotal(data.totalElements) // 修改总数
    setLoading(false)
  }

  // 省级联动，需要在省级变化之后再获取市数据，市取获取数据根据上一级的id来获取
  // 使用状态将每次获取的数据存储起来，使用插值表达式map遍历插入,重新选择省时应该清除其他市区状态
  // 获得市数据
  const provincial = async (id: string) => {
    setLoading(true)
    // 省级发生改变清除市区的选择，修改的是form表单的name属性
    form.setFieldsValue({ districtCode: "", cityCode: "" })
    const res = await MunicipalLevel(id)
    setCityName(res)

    // septicityData([])
    setLoading(false)
  }
  // 获取区函数
  const region = async (id: string) => {
    setLoading(true)
    // 市发生改变清除区的选择
    form.setFieldsValue({ districtCode: "" })
    const res = await MunicipalLevel(id)
    septicityData(res)
    setLoading(false)
  }

  return (
    <Card>
      {/* 头部表单 */}
      <Form form={form} layout="inline" onFinish={queryCondition}>
        <Form.Item name="provinceCode" style={{ marginBottom: 20 }}>
          <Select
            placeholder="请选择省"
            style={{ width: 200 }}
            onChange={provincial}
          >
            {/* 具体数据写在这里，需要发送请求获取，使用 <Option>包裹可以渲染到下拉列表 */}
            {provinceData.map((provinceData: any) => {
              return (
                <option value={provinceData.value} key={provinceData.id}>
                  {provinceData.name}
                </option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item name="cityCode" style={{ marginBottom: 20 }}>
          <Select
            placeholder="请选择市"
            style={{ width: 200 }}
            onChange={region}
          >
            {CityName.map((CityName: any) => {
              return (
                <option value={CityName.value} key={CityName.id}>
                  {CityName.name}
                </option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item name="districtCode" style={{ marginBottom: 20 }}>
          <Select placeholder="请选择区" style={{ width: 200 }}>
            {cityData.map((cityData: any) => {
              return (
                <option value={cityData.value} key={cityData.id}>
                  {cityData.name}
                </option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item name="hosname" style={{ marginBottom: 20 }}>
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode" style={{ marginBottom: 20 }}>
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype" style={{ marginBottom: 20 }}>
          <Select placeholder="医院类型" style={{ width: 200 }}>
            {values.map((values: any) => {
              return (
                <option value={values.value} key={values.id}>
                  {values.name}
                </option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item name="status" style={{ marginBottom: 20 }}>
          <Select placeholder="医院状态" style={{ width: 200 }}>
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 20 }}>
          <Button
            type="primary"
            htmlType="submit"
            icon={<SearchOutlined />}
            className="hospital-btn m"
            style={{ marginRight: 10 }}
          >
            查询
          </Button>
          <Button
            onClick={() => {
              // 渲染form表单为空
              form.resetFields()
              paging(1, 5)
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        // 添加key
        rowKey="id"
        // 允许表格出现滚动条
        scroll={{ x: 1500 }}
        // 设置表格边框
        bordered
        // 分页器
        pagination={{
          current: page,
          // 指定每页显示多少条
          pageSize,
          //总共有多少数据， 会根据传入的total计算页数，一页默认十条
          total,

          // 展示动态修改一页多少条数据
          showSizeChanger: true,

          // 指定每页可以显示多少条数据
          pageSizeOptions: ["2", "5", "8"],

          // 是否可以跳转至某页
          showQuickJumper: true,

          // 显示总数据量
          showTotal: (total) => {
            return `一共${total}家医院`
          },
          // 切换页面及pagesize发生改变时发送请求修改页码
          onChange: paging,
        }}
      />
    </Card>
  )
}

export default Index
